package ldh.im.fxbase.service;

import ldh.im.dto.base.SuccessResp;
import ldh.im.dto.business.P2gTextMessage;
import ldh.im.dto.enmus.MessageType;
import ldh.im.fxbase.dao.GroupDao;
import ldh.im.fxbase.dao.MessageDao;
import ldh.im.fxbase.dao.UserDao;
import ldh.im.fxbase.pojo.DbMessage;
import ldh.im.fxbase.pojo.ImGroup;
import ldh.im.fxbase.pojo.ext.MessageStatus;
import ldh.im.fxbase.util.BeanFactory;

import java.sql.SQLException;
import java.util.Date;

public class P2gMessageReceiveHandle implements MessageReceiveHandle<SuccessResp, P2gTextMessage> {

    private MessageDao messageDao = BeanFactory.getInstance().getBean(MessageDao.class);
    private UserDao  userDao = BeanFactory.getInstance().getBean(UserDao.class);
    private GroupDao groupDao = BeanFactory.getInstance().getBean(GroupDao.class);

    @Override
    public SuccessResp handleMessage(P2gTextMessage message) throws SQLException {
        DbMessage dbMessage = buildDbMessage(message);
        messageDao.saveMessage(dbMessage);
        return new SuccessResp();
    }

    private DbMessage buildDbMessage(P2gTextMessage message) throws SQLException {
        DbMessage dbMessage = new DbMessage();
        dbMessage.setServerId(message.getLocalSeq());
        dbMessage.setStatus(MessageStatus.received);
        dbMessage.setAttachStatus(MessageStatus.created);
        dbMessage.setFromUserId(message.getFromUserId());
        dbMessage.setVersion(1L);
        dbMessage.setMessageType(message.getMessageType());
        handleBytes(message);
        dbMessage.setContent(message.getContent());

        ImGroup imGroup = groupDao.getImGroupById(message.getGroupId());
        dbMessage.setGroupId(imGroup.getId());
        dbMessage.setCreateDateTime(message.getCreateDateTime());
        dbMessage.setUpdateTime(new Date());
        return dbMessage;
    }

    private void handleBytes(P2gTextMessage message) {
        if(message.getMessageType() == MessageType.Image) {
            
        }
    }

}
